<template>
  <div id="job">
    <el-form label-width="250px" ref="queryForm" :model="query">
      <el-row>
        <el-col :lg="6">
          <el-form-item label-width="70px" style="line-height:40px;position:relative;font-size:14px;float:left">
            <el-date-picker
                v-model="query.recordDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :lg="6">
          <el-form-item  label-width="70px" style="line-height:40px;position:relative;font-size:14px;float:left">
            <el-select v-model="query.categoryId" placeholder="请选择分类" clearable >
              <el-option
                v-for="item in categoryData"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :lg="3" style="width:600px;position:absolute;left:132px;text-align:left" >
          <el-button type="warning" @click="selectByDate" icon="el-icon-search" style="padding: 12px 20px; width:120px;margin-left: 600px;">查询</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="text-align: left; padding:12px 70px" >
      <el-button style="margin-right:50px"
        type="success"
        @click="addLog"
        icon="el-icon-circle-plus-outline"
        >新增日志</el-button
      >
      <el-button type="primary" style="margin-right:50px" @click="addCategory" icon="el-icon-circle-plus-outline"
        >新增分类</el-button>
      <el-button type="primary" style="margin-right:50px" @click="updateLog" icon="el-icon-edit-outline"
        >修改日志</el-button
      >
      <el-button type="danger" @click="deleteLog" icon="el-icon-delete"
        >删除日志</el-button
      >
      <el-button type="danger" @click="deleteCategory" icon="el-icon-delete">
        删除分类
      </el-button>
    </el-row>

    <el-dialog title="工作日志编辑" :visible.sync="dialogVisible" width="50%" >
      <el-form :model="addData" :rules="formRules" ref="logForm">
        <el-form-item label="日期" prop="recordDate" >
          <el-date-picker
            v-model="addData.recordDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="left:14px"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-time-select
            v-model="addData.startTime"
            :picker-options="{
              start: '08:30',
              step: '00:01',
              end: '17:30'
            }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-select
            v-model="addData.endTime"
            :picker-options="{
              start: '08:30',
              step: '00:01',
              end: '17:30',
              minTime: addData.startTime
            }"
            placeholder="选择时间"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="addData.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作内容" prop="content">
          <el-input
            v-model="addData.content"
            type="textarea"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分类删除" :visible.sync="delDialogVisible" width="50%" >
      <el-form :model="delData"  ref="delCategoryForm">
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="delData.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="delSubmit">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分类新增" :visible.sync="addCategoryVisible" width="50%" >
      <el-form :model="addCategoryData" :rules="categoryFormRules" ref="categoryForm">
        <el-form-item label="分类" prop="categoryName">
          <el-input
            v-model="addCategoryData.categoryName"
            type="textarea"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addCategorySubmit">提 交</el-button>
      </div>
    </el-dialog>

    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="50">
      </el-table-column>
      <el-table-column prop="categoryName" label="分类" width="100">
      </el-table-column>
      <el-table-column prop="recordDate" label="日期" width="100">
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="100">
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="100">
      </el-table-column>
      <el-table-column prop="content" label="工作内容" width="800">
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      op: "add",
      selectData: [],
      dialogVisible: false,
      delDialogVisible: false,
      addCategoryVisible: false,
      categoryData: [],
      addCategoryData:{
        categoryName:''
      },
      delData:{
        categoryId:''
      },
      addData: {
        id: '',
        userId:'',
        categoryId: '',
        recordDate: '',
        startTime: '',
        endTime: '',
        content: ''
      },
      tableData: [],
      categoryFormRules: {
        categoryName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ]
      },
      formRules: {
        recordDate: {
          required: true,
          message: "请选择工作日期",
          trigger: "blur"
        },
        startTime: {
          required: true,
          message: "请选择开始时间",
          trigger: "blur"
        },
        categoryId: {
          required: true,
          message: "请选择分类",
          trigger: "blur"
        },
        endTime: { required: true, message: "请选择结束时间", trigger: "blur" },
        content: [
          { required: true, message: "请输入工作内容", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ]
      },
      query: {
        recordDate: [],
        categoryId: ""
      },
      selectId:[]
    };
  },
  created() {
    this.selectCategory();
    this.selectAll();
    this.getCurrentDate();
    this.$nextTick(() => {
      this.addData.userId = this.$store.state.userId;
    });
    console.log(this.$store.state.userId);

  },
  computed: {
    ...mapState(['userId','token'])
  },
  methods: {
    getCurrentDate() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}`;
      this.$set(this.addData, "recordDate", defaultDate);
                },

    
    selectCategory(){
      this.$axios({
        method: "get",
        url: "http://localhost:8889/category"
      })
        .then(res => {
          console.log("拿到的响应是：", res);
          this.categoryData = res.data.data;
        })
        .catch(err => {
          console.log("错误为:", err);
        });
    },
    selectAll() {
      this.$axios({
        method: "get",
        url: "http://localhost:8889/mylog/selectAll"
      })
        .then(res => {
          console.log("拿到的响应是：", res);
          this.tableData = res.data;
          this.convertCategoryIdsToNames()
        })
        .catch(err => {
          console.log("错误为:", err);
        });
    },

 convertCategoryIdsToNames() {
    const categoryMap = this.categoryData.reduce((acc, category) => {
      acc[category.id] = category.categoryName;
      return acc;
    }, {});

    console.log("categoryMap:", categoryMap); // 调试 categoryMap

    this.tableData = this.tableData.map(item => ({
      ...item,
      categoryName: categoryMap[item.categoryId] || 'Unknown Category'
    }));
  },

    addLog() {
      this.dialogVisible = true;
      this.op = "add";
    },
    addCategory(){
      this.addCategoryVisible = true;
    },
    addCategorySubmit(){
      this.$refs["categoryForm"].validate(v => {
        if (v) {
          this.$axios({
        method: "post",
        url: "http://localhost:8889/category/add",
        data: this.addCategoryData
      })
        .then(res => {
          console.log("拿到的响应是：", res);
          this.selectCategory();
          this.$notify({
            title: '成功',
            message: '新增分类成功',
            type: 'success'
          });
          this.addCategoryVisible = false;
        })
        .catch(err => {
          console.log("错误为:", err);
       });
        }
      });

    },
    submit() {
      this.$refs["logForm"].validate(v => {
        if (v) {
          this.submitLog();
        }
      });
    },

    submitLog() {
      if (this.op == "add") {
        this.$axios({
          method: "post",
          url: "http://localhost:8889/mylog/add",
          data: this.addData
        })
          .then(res => {
            console.log("拿到的响应是：", res);
            this.dialogVisible = false;
            this.selectAll();
            this.$refs.logForm.resetFields();
          })
          .catch(err => {
            console.log("错误为:", err);
          });
      } else if (this.op == "edit") {
        this.$axios({
          method: "post",
          url: "http://localhost:8889/mylog/updateRecord",
          data: this.addData
        })
          .then(res => {
            console.log("拿到的响应是：", res);
            this.selectAll();
            this.$refs.logForm.resetFields();
            this.dialogVisible = false;
          })
          .catch(err => {
            console.log("错误为:", err);
          });
      }
    },
    cancel() {
      this.$refs.logForm.resetFields();
      this.dialogVisible = false;
    },
    updateLog() {
      this.op = "edit";
      if (this.selectData.length != 1) {
        this.$message.error("请勾选要修改的一条记录！");
      } else {
        console.log("row data is:", this.selectData[0]);
        for (var key in this.selectData[0]) {
          this.addData[key] = this.selectData[0][key];
        }

        this.dialogVisible = true;
      }
    },
    handleSelectionChange(row) {
      this.selectData = row;
    },
    selectByDate() {
      console.log(this.query.recordDate)
      if (this.query.recordDate != null || this.query.recordDate != "" || this.query.categoryId != null) {
        this.$axios({
          method: "post",
          url: "http://localhost:8889/mylog/selectByDate",
          data:this.query
        }).then(res => {
            console.log("拿到的响应是：", res);
            this.tableData = res.data;
            this.convertCategoryIdsToNames()
          }).catch(err => {
            console.log("错误为:", err);
          })
      } else {
        this.selectAll();

      }
    },
    deleteLog() {
      console.log("this.selectData is:", this.selectData);
      if (this.selectData.length < 1) {
        this.$message.error("请勾选要删除的记录");
      } else {
        var len = this.selectData.length;
        console.log("当前勾选的数据条数为:", len);
        for( var i=0; i<len; i++){
          this.selectId.push(this.selectData[i]["id"]);
        }
        console.log("当前勾选的数据id为:", this.selectId);
        this.$confirm("确认是否删除当前数据！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$axios.post("http://localhost:8889/mylog/deleteById/"+this.selectId,
          )
            .then(res => {
              console.log("拿到的响应是：", res);
              this.selectAll();
            })
            .catch(err => {
              console.log("错误为:", err);
            });
        });
      }
    },

    deleteCategory(){
      this.delDialogVisible = true;
    },
    delSubmit(){
      this.$axios.get("http://localhost:8889/category/"+this.delData.categoryId)
        .then(res => {
          console.log("删除拿到的响应是：", res);
          if(res.data === 0){
            this.$notify.error({
              title: '错误',
              message: '请删除此分类下的日志'
            });
          }
          if(res.data === 1){
            this.$notify({
              title: '成功',
              message: '删除分类成功',
              type: 'success'
            });
            this.selectCategory()
            this.$refs.delCategoryForm.resetFields();
            this.delDialogVisible = false;
          }
        })
        .catch(err => {
          console.log("错误为:", err);
        });
    }

  }
};
</script>

<style scoped>
/* .queryClass {
  margin-left: 300px;
} */
</style>
